package com.pospi.xstore.ui.cash_ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.RefundGoodsDetailAdapter;
import com.pospi.xstore.dao.OrderDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.CashierMsgDto;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.OrderBeen;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.dto.PayBeen;
import com.pospi.xstore.greendao.OrderBeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.http.MaxNO;
import com.pospi.xstore.http.UploadData;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.PareseJson;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseActivity {

    @Bind(R.id.refund_detail_btn)
    Button refundDetailBtn;
    @Bind(R.id.maxno)
    TextView maxno;
    @Bind(R.id.data)
    TextView data;
    @Bind(R.id.cashier_name)
    TextView cashierName;
    @Bind(R.id.sale_type)
    TextView saleType;
    @Bind(R.id.sale_state)
    TextView saleState;
    @Bind(R.id.goods_detail)
    ListView goodslv;
//    @Bind(R.id.pay_type_way)
//    TextView payTypeWay;
//    @Bind(R.id.pay_type_money)
//    TextView payTypeMoney;
    @Bind(R.id.goods_num)
    TextView goodsNum;
    @Bind(R.id.discount_total)
    TextView discountTotal;
    @Bind(R.id.yy_money)
    TextView yyMoney;
    @Bind(R.id.ss_money)
    TextView ssMoney;
    @Bind(R.id.zl_money)
    TextView zlMoney;
    @Bind(R.id.ll_lay)
    LinearLayout ll_lay;
    private OrderBeen orderDto;

    private RefundGoodsDetailAdapter adapter;
    private List<GoodsDto> goodsDtos;
    private int payType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_order_detail);
        setTitle("订单详情");
        ButterKnife.bind(this);
        orderDto = (OrderBeen) getIntent().getSerializableExtra(RefundActivity.REFUNDS);
        init();

    }

    public void init() {
        maxno.setText(String.valueOf(orderDto.getMaxNo()));
        data.setText(orderDto.getCheckoutTime());
        if (orderDto.getOrderType() == Constant.ORDERTYPE_REFUND) {
            saleType.setText("退货");
            saleType.setTextColor(getResources().getColor(R.color.red));
            refundDetailBtn.setBackgroundColor(getResources().getColor(R.color.grey));
            refundDetailBtn.setClickable(false);
        } else {
            saleType.setText("销售");
        }
        goodsDtos = SaveOrderInfo.changeToList(orderDto.getOrder_info());
        adapter = new RefundGoodsDetailAdapter(goodsDtos, getApplicationContext());
        goodslv.setAdapter(adapter);
        fixListViewHeight(goodslv);
        cashierName.setText(orderDto.getCashiername());
        List<PayBeen> payBeens = new Gson().fromJson(orderDto.getPayway(), new TypeToken<List<PayBeen>>() {
        }.getType());

        String way = "";
        for (PayBeen been : payBeens) {
            TextView view = new TextView(this);
            view.setText(been.getName()+"                  "+been.getSs());
            view.setTextSize(16);
            ll_lay.addView(view);
        }
//        payTypeWay.setText(way);
//        payTypeMoney.setText(String.valueOf(orderDto.getYs_money()));
        int num = 0;
        double discount = 0;
        for (int i = 0; i < goodsDtos.size(); i++) {
            num += goodsDtos.get(i).getNum();
            discount += goodsDtos.get(i).getDiscount();
        }
        goodsNum.setText(String.valueOf(num));
        yyMoney.setText(String.valueOf(orderDto.getYs_money()));
        ssMoney.setText(String.valueOf(orderDto.getSs_money()));
        zlMoney.setText(String.valueOf(orderDto.getZl_money()));
        discountTotal.setText(String.valueOf(discount));
    }

    @OnClick(R.id.refund_detail_btn)
    public void onClick() {
        if (orderDto.getHasReturnGoods() == Constant.hasReturnGoods_Yes) {
            showToast("该订单已经退货！");
        } else {
            showRefundDialog();
        }
        refundDetailBtn.setClickable(false);
    }

    public void showRefundDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("您确定要退货吗？")
                .setMessage("点击[确定]后，完成退款操作！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (orderDto.getPayway().equals(Constant.PAYMENT_WEIXIN_String)) {
                            payType = Constant.PAYMENT_WEIXIN;
//                            Intent intent = new Intent(OrderDetailActivity.this, CaptureActivity.class);
//                            startActivityForResult(intent, Constant.PAYMENT_WEIXIN);
//                            refund("wx");
                        } else if (orderDto.getPayway().equals(Constant.PAYMENT_ALIPAY_String)) {
                            payType = Constant.PAYMENT_ALIPAY;
//                            Intent intent = new Intent(OrderDetailActivity.this, CaptureActivity.class);
//                            startActivityForResult(intent, Constant.PAYMENT_ALIPAY);
//                            refund("ali");
                        } else {
                            payType = Constant.PAYMENT_CASH;
                            OrderBeen been = App.getInstance().getDaoSession().getOrderBeenDao().queryBuilder().where(OrderBeenDao.Properties
                                    .MaxNo.eq(orderDto.getMaxNo())).unique();
                            been.setHasReturnGoods(Constant.hasReturnGoods_Yes);
                            App.getInstance().getDaoSession().getOrderBeenDao().update(been);

                            showToast("退货成功");
                            addorderinfo();
                            startActivity(RefundActivity.class);

                            finish();
                        }
//                        if (new OrderDao(getApplicationContext()).updateOrderInfo(orderDto.getMaxNo())) {
//
//                        } else {
//                            showToast("退货失败");
//                            refundDetailBtn.setClickable(true);
//                        }

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        dialog.show();
    }

    public void addorderinfo() {





        /**
         * 给服务器写入一条记录
         */
        int whichOne = getSharedPreferences("islogin", MODE_PRIVATE).getInt("which", 0);


//        CashierMsgDto cashierMsgDto = new PareseJson().parese(
//                getSharedPreferences("cashierMsgDtos", MODE_PRIVATE)
//                        .getString("cashierMsgDtos", ""))
//                .get(whichOne);
        String cashier_name = SPHelper.getInstance().getString(Constant.STORE_NAME);
        String cashier_nun = SPHelper.getInstance().getString(Constant.STORE_ID);

        String shopId = SPHelper.getInstance().getString(Constant.STORE_ID);
        OrderBeen orderDto11 = new OrderBeen();
        List<GoodsDto> goodsDtos = SaveOrderInfo.changeToList(orderDto.getOrder_info());
        for (int i = 0; i < goodsDtos.size(); i++) {
            double num = goodsDtos.get(i).getNum();
            goodsDtos.get(i).setNum(-num);
        }
        String listinfo = SaveOrderInfo.changeGoodDtoToJson(goodsDtos);
        orderDto11.setOrder_info(listinfo);
        orderDto11.setPayway(orderDto.getPayway());
        orderDto11.setTime(GetData.getYYMMDDTime());
        orderDto11.setSs_money(-orderDto.getYs_money());
        orderDto11.setYs_money(-orderDto.getYs_money());
        orderDto11.setZl_money(0);
        orderDto11.setCashiername(SPHelper.getInstance().getString(Constant.COUNT_NAME));
        orderDto11.setCashiernumber(SPHelper.getInstance().getString(Constant.USER_ID));
        orderDto11.setShop_id(shopId);
        orderDto11.setOrderType(Constant.ORDERTYPE_REFUND);
        orderDto11.setMaxNo(MaxNO.getMaxNo(getApplicationContext()));
        orderDto11.setCheckoutTime(GetData.getDataTime());
        orderDto11.setDetailTime(GetData.getHHmmssTimet());
        orderDto11.setHasReturnGoods(Constant.hasReturnGoods_Yes);
        orderDto11.setIfFinishOrder(Constant.YES);
        orderDto11.setSearchTime(GetData.getSearchTime());
        orderDto11.setUpStatus(Constant.UP_NO);
        orderDto11.setVipNumber(orderDto.getVipNumber());
        OrderBeenDao dao = App.getInstance().getDaoSession().getOrderBeenDao();
        dao.insert(orderDto11);
        UploadData.upOrder(this, orderDto11,orderDto.getPayway());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String code = null;
        switch (requestCode) {
            case Constant.PAYMENT_ALIPAY:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
                        if (code.equalsIgnoreCase(orderDto.getOut_trade_no().trim())) {
                            showDialog("正在退款，请等待");
                            refund("ali");
                        } else {
                            showToast("商户单号验证失败，不可退款");
                        }
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("退款失败，未获取到条形码");
                }

                break;
            case Constant.PAYMENT_WEIXIN:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
                        if (code.equalsIgnoreCase(orderDto.getOut_trade_no().trim())) {
                            showDialog("正在退款，请等待");
                            refund("wx");
                        } else {
                            showToast("商户单号验证失败，不可退款");
                        }
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("退款失败，未获取到条形码");
                }
                break;
        }
    }

    public void refund(String mode) {
        String value = getSharedPreferences("Token", MODE_PRIVATE).getString("value", "");
        String[] names = value.split("\\,");
        String uid = names[1];
        RequestParams params = new RequestParams();
        params.put("pay_mode", mode);
        String money = String.valueOf(orderDto.getSs_money());
        if (mode.equals("wx")) {
            money = String.valueOf((int) (orderDto.getSs_money() * 100));
        }
        params.put("resund_fee", money);
        params.put("total_fee", money);
        params.put("transaction_id", orderDto.getPayReturn());
        params.put("uid", uid);
        LoadServer.getConnect(getApplicationContext(), Api.REFUND, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                closeDialog();
                Log.i("refund", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getInt("Result") == 1) {
                        showToast(object.getString("Message"));
                        new OrderDao(getApplicationContext()).updateOrderInfo(orderDto.getMaxNo());
                        addorderinfo();
                        finish();
                    } else {
                        showToast(object.getString("Message"));
                        refundDetailBtn.setClickable(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                closeDialog();
                Log.i("refundfailure", new String(bytes));
                refundDetailBtn.setClickable(true);
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    showToast(object.getString("Message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private Dialog dialog;

    public void showDialog(String msg) {
        if (dialog == null) {
            dialog = WaitingDialog.createLoadingDialog(this, msg);
            dialog.show();
        }
    }

    public void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listViewItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

}
